package LeetCode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomRedPacketGenerator {

    public List<Double> generateRandomRedPackets(double totalAmount, int numPackets) {
        List<Double> packets = new ArrayList<>();
        Random random = new Random();
        int curNumPackets =numPackets - 1;

        for (int i = 0; i < curNumPackets; i++) {
            // 计算最小和最大金额
            double minAmount = 0.01;  // 每个红包至少0.01元
            double maxAmount = totalAmount / numPackets * 2;

            // 随机生成红包金额
            double amount = round(random.nextDouble() * (maxAmount - minAmount) + minAmount);

            packets.add(amount);

            // 更新红包总金额和个数
            totalAmount -= amount;
            numPackets--;
        }

        // 最后一个红包的金额等于剩余的红包金额
        packets.add(round(totalAmount));

        return packets;
    }

    private double round(double value) {
        double scale = Math.pow(10, 2);
        return Math.round(value * scale) / scale;
    }

    public static void main(String[] args) {
        double totalAmount = 520.0;  // 红包总金额为10元
        int numPackets = 4;  // 红包个数为6

        RandomRedPacketGenerator generator = new RandomRedPacketGenerator();
        List<Double> redPackets = generator.generateRandomRedPackets(totalAmount, numPackets);
        System.out.println(redPackets);
    }
}
